package main.kotlin.webMagic


import java.sql.Connection
import java.sql.DriverManager
import java.sql.Statement



class DownloadLog(val name: String = "Link") {
    private val database = "jdbc:sqlite:logged.db"
    private var id=0

    private var connection : Connection? = null
    private var statement: Statement? = null

    init {
        this.connect()
        id = lastId()
        this.close()
    }

    fun connect() {
        this.connection = DriverManager.getConnection(database)
        this.statement = this.connection!!.createStatement()
    }

    fun lastId(): Int {

        if (!exists()) {
            this.create()
            return 0
        }

        val lastid = statement!!.executeQuery("select id from ${this.name} order by id desc limit 1")

        when (lastid.fetchSize) {
            0 -> return 0
            else -> return lastid.getInt("id") + 1
        }
    }

    fun exists(): Boolean {
        val existsance = statement!!.executeQuery("select name from sqlite_master where type='table' and name = '${this.name}'")
        val tmp = existsance.next()
        return tmp
    }

    fun create(){

        if (!this.exists()) {
            statement!!.execute("create table ${this.name} (id integer, link text, title text)")
        }

    }

    fun insert(link: String, title: String) {
        statement!!.execute("insert into ${this.name} values (${this.id}, '$link', '$title')")
        id++
    }

    fun check(link: String): Boolean {
        val exists = statement!!.executeQuery("select * from ${this.name} where link = '$link'")

        return exists.next()
    }

    fun close() {
        connection!!.close()
    }
}


